'''
Created on 11/03/2010

@author: igonzalez
'''

from django.http import HttpResponse
from format.utils import  getResponseFormat, generateResponse

from os import path
from xml.dom import minidom
import copy
import urllib

from GIC.Channels.Items.PhotoItem import *
from GIC.Channels.GenericChannel import *

PAGE = 0
N_ELEMS = 20

class CphotoLoader(object):
    '''
    classdocs
    '''

    def __init__(self):
        self.array = []
        self.count = 0
        
        #this function generates a geonode array parsing the xml that openadaptor has generated
    def generate_Array(self, channel,category):
        channel = channel.lower()
        category = category.lower()
        direccion = self.getPath()
        xml = str(direccion) + "/agregator_files/xmlConf/" + channel + "_" + category + ".xml"
        xmldoc = minidom.parse(xml)
        son = xmldoc.firstChild
        self.count = int(son.getAttribute('size'))
        photoList = son.getElementsByTagName('photo')
        i = 0
        while(i < self.count):
            tempPhoto = PhotoItem()
            tempLatitude = ""
            tempLongitude = ""
            tempPhoto.id = photoList[i].getAttribute('id')
            title = photoList[i].getElementsByTagName('title')
            if (len(title) > 0):
                if (title[0].firstChild != None):   
                    tempPhoto.name = title[0].firstChild.nodeValue
            desc = photoList[i].getElementsByTagName('description')
            if (len(desc) > 0):
                if (desc[0].firstChild != None):   
                    tempPhoto.description = desc[0].firstChild.nodeValue
            url = photoList[i].getElementsByTagName('url')
            if (len(url) > 0):
                if (url[0].firstChild != None):    
                    tempPhoto.external_info['info_url'] = url[0].firstChild.nodeValue
            path = photoList[i].getElementsByTagName('file')
            if (len(path) > 0):
                if (path[0].firstChild != None):     
                    tempPhoto.external_info['photo_url'] = path[0].firstChild.nodeValue
                    tempPhoto.external_info['photo_thumb'] = str(path[0].firstChild.nodeValue).replace('/medium/', '/small/')
            longitude = photoList[i].getElementsByTagName('longitude')
            if (len(longitude) > 0):
                if (longitude[0].firstChild != None): 
                    tempLongitude = longitude[0].firstChild.nodeValue
            latitude = photoList[i].getElementsByTagName('latitude')
            if (len(latitude) > 0):
                if (latitude[0].firstChild != None): 
                    tempLatitude = latitude[0].firstChild.nodeValue
            tempPhoto.position = {'latitude' : tempLatitude, 'longitude' : tempLongitude}        
            since = photoList[i].getElementsByTagName('date')
            if (len(since) > 0):
                if (since[0].firstChild != None):   
                    tempPhoto.position['since'] = since[0].firstChild.nodeValue
                    tempPhoto.since = since[0].firstChild.nodeValue
            tempPhoto.icon = "/social/layer/" + channel + "/icon"        
            self.array.append(copy.deepcopy(tempPhoto))
            i = i + 1 
        return self.array  
         
            #this function manages the geonode generation with httpresponse only useful for petitions without client
    def generate_all(self, channel,category, request): 
        channel = str(channel.lower())
        category = str(category.lower())   
        format = getResponseFormat (request)  
        #calls the generate array function            
        self.generate_Array(channel,category)
        #makes the pagination and returns a HttpResponse with the geonodes using a template
        f, t, page, elems = self.get_limits(request)
        array2 = copy.deepcopy(self.array)
        self.array = self.select_limits (f, t, array2)
        data = {'code'    : '200',
                'id_type' : str(category) + 's',
                'photos'  : self.array,
                'page'    : page,
                'elems'   : len(self.array),
                'type'    : str(category) + "_list" }
        return generateResponse(format, data, "photo/list")     
            
    def select_limits(self, from_limit, to_limit, nodes):
        return nodes[from_limit:to_limit]        
            
    def get_limits(self, request):
        if "page" in request.REQUEST:
            page = request.REQUEST["page"]
        else:
            page = None
        if "elems" in request.REQUEST:
            elems = request.REQUEST["elems"]
        else:
            elems = None
        try:
            page = int(page) - 1
            if page < 0:
                raise ValueError()
        except:
            page = PAGE
        try:
            elems = int(elems)
            if elems < 0:
                raise ValueError()
        except:
            elems=N_ELEMS
        f = elems * page
        t = f + elems
        return (f, t, page+1, elems)        
               
    def getPath(self):
        direccion2 = path.dirname(path.abspath(__file__))
        return direccion2
